/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ido.client;

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.VerticalSplitPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 *
 * @author greenido
 */
public class MainPanel extends DockPanel implements KeyboardListener {

    private VerticalPanel targilimPanel;
    private HorizontalPanel rowPanel;
    private HorizontalPanel buttonsPanel;
    private ScrollPanel targilimScrolPanel;
    
    private Label targilLabel;
    private Button rightButton;
    private Button wrongButton;
    private boolean useCorrentAnswer; // true = correct / false=wrong
    private int noTargilim; // TODO read it from conf. screen/file
    private int curTaril;
    private int mistakes;
    private long startTime;
    private long endTime;
    
    private boolean isItFinished;

    /**
     * Ctor - start the action
     */
    public MainPanel() {
        initUI();
        isItFinished = false;
    }

    private void initUI() {
        noTargilim = 10;
        curTaril = 0;
        mistakes = 0;
        targilimPanel = new VerticalPanel();
        rightButton = new Button("Correct");
        rightButton.setTitle("Right");
        rightButton.addKeyboardListener(this);
        rightButton.addClickListener(new ClickListener() {
            public void onClick(Widget but) {
                solveLastTargil(but.getTitle());
                addTrgil();
            }
        });
        wrongButton = new Button("Wrong");
        wrongButton.setTitle("Wrong");
        wrongButton.addKeyboardListener(this);
        wrongButton.addClickListener(new ClickListener() {

            public void onClick(Widget but) {
                solveLastTargil(but.getTitle());
                addTrgil();
            }
        });
        buttonsPanel = new HorizontalPanel();
        buttonsPanel.add(wrongButton);
        buttonsPanel.add(rightButton);
        Label header = new Label("A quick run on " + noTargilim + " Exercise", true);
        header.setStyleName("header");
        add(header, DockPanel.NORTH);
        
        targilimScrolPanel = new ScrollPanel(targilimPanel);  
        targilimScrolPanel.setHeight("200px");   
        targilimScrolPanel.setWidth("200px");
        
        add(targilimScrolPanel, DockPanel.CENTER);
        add(buttonsPanel, DockPanel.SOUTH);
        addTrgil();
                
         DeferredCommand.addCommand(new Command() {
            public void execute() {
                rightButton.setFocus(true);
            }
        });
    }

    public HorizontalPanel getButtonsPanel() {
        return buttonsPanel;
    }

    public int getCurTaril() {
        return curTaril;
    }

    public long getEndTime() {
        return endTime;
    }

    public long getStartTime() {
        return startTime;
    }

    
    private int getWrongAns(int ans) {
        int wrongAns = 0;
        int ranNo = Random.nextInt(4);
        if (ranNo == 0) {
            ranNo = -1;
        }
        if (Random.nextBoolean()) {
            wrongAns = ans - ranNo;
        } else {
            wrongAns = ans + ranNo;
        }
        return wrongAns;
    }

    private void solveLastTargil(String title) {
        Label badAns = new Label();
        badAns.setStyleName("bad-ans");
        if (title.equalsIgnoreCase("Wrong") && useCorrentAnswer) {
            mistakes++;
            rowPanel.add(badAns); // change to nice icon
        } else if (title.equalsIgnoreCase("Right") && !useCorrentAnswer) {
            mistakes++;
            rowPanel.add(badAns); // change to nice icon
        } else {
            Label goodAns = new Label();
            goodAns.setStyleName("good-ans");
            rowPanel.add(goodAns);
        }

    }

    /**
     * Add tragil and show if the last one was good or not..
     */
    private void addTrgil() {
        int first = Random.nextInt(20); // TODO - change it to properties
        int second = Random.nextInt(15);
        int operator = Random.nextInt(4);

        String opStr = "";
        int ans = 0;
        switch (operator) {
            case 0:
                opStr = "+";
                ans = first + second;
                break;
            case 1:
                opStr = "-";
                ans = first - second;
                break;
            case 2:
                opStr = "*";
                ans = first * second;
                break;
            case 3:
                opStr = "/";
                ans = first * second;
                int tmp = first;
                first = ans;
                ans = tmp;
                break;
        }
        StringBuffer sb = new StringBuffer("" + first);
        sb.append(" ");
        sb.append(opStr);
        sb.append(second);
        sb.append(" = ");

        useCorrentAnswer = true;
        if (Random.nextBoolean()) {
            // lets have a wrong answer (in 50% of the times)
            int wrongAns = getWrongAns(ans);
            if (ans != wrongAns) {
                useCorrentAnswer = false;
                ans = wrongAns;
            }
        }
        sb.append(ans);
        String targilStr = sb.toString();
        System.out.println("tar: " + targilStr);

        targilLabel = new Label(targilStr);
        targilLabel.setStyleName("targil-label");
        rowPanel = new HorizontalPanel();

        if (curTaril < noTargilim) {
            rowPanel.add(targilLabel);
            targilimPanel.add(rowPanel);  
            curTaril++;
            targilimScrolPanel.setScrollPosition( targilimScrolPanel.getScrollPosition() + 45); 
            
            if (curTaril == 1) {
                // first one - so let start the counter
                startTime = System.currentTimeMillis();
            }
        } else {
            // finish the targil
            endTime = System.currentTimeMillis();
            showGrade(endTime - startTime);
            isItFinished = true;
        }
    }

    public boolean isIsItFinished() {
        return isItFinished;
    }

    public int getMistakes() {
        return mistakes;
    }

    public int getNoTargilim() {
        return noTargilim;
    }
  
    /**
     * Show the user how good/bad they did
     * @param time
     */
    private void showGrade(long time) {
        rightButton.setEnabled(false);
        wrongButton.setEnabled(false);
        float tookTime = (time / 1000.0f);
        tookTime = (float) (Math.floor(tookTime * 100) / 100);
        String grade = getGradeStr(tookTime);
        grade += ", you did it in: " + tookTime + " seconds & " + mistakes + " mistakes.";
        targilLabel = new Label(grade, true);
        targilLabel.setStyleName("your-grade");
        add(targilLabel, DockPanel.SOUTH);
    }

    private String getGradeStr(float tookTime) {
        if (tookTime < 10) {
            return "WOW!";
        } else if (tookTime < 15) {
            return "Nice!";
        } else if (tookTime < 20) {
            return "Good Job!";
        } else if (tookTime < 25) {
            return "I know you can do better";
        }
        return "Well";
    }

    public void onKeyDown(Widget arg0, char arg1, int arg2) {
        //TODO
    }

    public void onKeyPress(Widget sender, char keyCode, int modifiers) {
        if (keyCode == 107) {// =k      [enter= ((keyCode == 13) && (modifiers == 0)) ]
            solveLastTargil("Right");
            addTrgil();
        } else if (keyCode == 106) { // =j
            solveLastTargil("Wrong");
            addTrgil();
        }
    }

    public void onKeyUp(Widget arg0, char arg1, int arg2) {
        //TODO
    }
}
